// 路径 

var path = "assets/";

var checkStatus = 0; //0表示未全选
$(document).ready(function() {
    // === 登录初始化 === //
    var url = document.location.href;
    var urlArr = url.split('?');
    console.log(urlArr[1]);
    var username = getCookie('username');
    var $account = $('.person-account');
    if (username != '') {
        $.ajax({
            url: "/epi/pidDepInfo", //'/epi/staff/staffs/'+thisId,//path+"json/staff.json",
            data: {
                username: username
            },
            type: "GET",
            dataType: 'json',
            success: function(data) {
                $account.data('id', data.pid);
                $account.data('dep-id', data.depid);
                $account.data('dep', data.dep);
                $account.text(username);
            },
            error: function() {
                setAlert('系统繁忙，请刷新重试');
            }
        });
    }


    // === Sidebar navigation === //

    $('.submenu > a').click(function(e) {
        e.preventDefault();
        var submenu = $(this).siblings('ul');
        var li = $(this).parents('li');
        var submenus = $('#sidebar li.submenu ul');
        var submenus_parents = $('#sidebar li.submenu');
        if (li.hasClass('open')) {
            if (($(window).width() > 768) || ($(window).width() < 479)) {
                submenu.slideUp();
            } else {
                submenu.fadeOut(250);
            }
            li.removeClass('open');
        } else {
            if (($(window).width() > 768) || ($(window).width() < 479)) {
                submenus.slideUp();
                submenu.slideDown();
            } else {
                submenus.fadeOut(250);
                submenu.fadeIn(250);
            }
            submenus_parents.removeClass('open');
            li.addClass('open');
        }
    });

    var ul = $('#sidebar > ul');

    $('#sidebar > a').click(function(e) {
        e.preventDefault();
        var sidebar = $('#sidebar');
        if (sidebar.hasClass('open')) {
            sidebar.removeClass('open');
            ul.slideUp(250);
        } else {
            sidebar.addClass('open');
            ul.slideDown(250);
        }
    });

    // === Resize window related === //
    $(window).resize(function() {
        if ($(window).width() > 479) {
            ul.css({ 'display': 'block' });
            $('#content-header .btn-group').css({ width: 'auto' });
        }
        if ($(window).width() < 479) {
            ul.css({ 'display': 'none' });
            fix_position();
        }
        if ($(window).width() > 768) {
            $('#user-nav > ul').css({ width: 'auto', margin: '0' });
            $('#content-header .btn-group').css({ width: 'auto' });
        }
    });

    if ($(window).width() < 468) {
        ul.css({ 'display': 'none' });
        fix_position();
    }

    if ($(window).width() > 479) {
        $('#content-header .btn-group').css({ width: 'auto' });
        ul.css({ 'display': 'block' });
    }

    // === Tooltips === //
    $('.tip').tooltip();
    $('.tip-left').tooltip({ placement: 'left' });
    $('.tip-right').tooltip({ placement: 'right' });
    $('.tip-top').tooltip({ placement: 'top' });
    $('.tip-bottom').tooltip({ placement: 'bottom' });

    // === Search input typeahead === //
    $('#search input[type=text]').typeahead({
        source: ['Dashboard', 'Form elements', 'Common Elements', 'Validation', 'Wizard', 'Buttons', 'Icons', 'Interface elements', 'Support', 'Calendar', 'Gallery', 'Reports', 'Charts', 'Graphs', 'Widgets'],
        items: 4
    });

    // === Fixes the position of buttons group in content header and top user navigation === //
    function fix_position() {
        var uwidth = $('#user-nav > ul').width();
        $('#user-nav > ul').css({ width: uwidth, 'margin-left': '-' + uwidth / 2 + 'px' });

        var cwidth = $('#content-header .btn-group').width();
        $('#content-header .btn-group').css({ width: cwidth, 'margin-left': '-' + uwidth / 2 + 'px' });
    }

    // === Style switcher === //
    $('#style-switcher i').click(function() {
        if ($(this).hasClass('open')) {
            $(this).parent().animate({ marginRight: '-=190' });
            $(this).removeClass('open');
        } else {
            $(this).parent().animate({ marginRight: '+=190' });
            $(this).addClass('open');
        }
        $(this).toggleClass('icon-arrow-left');
        $(this).toggleClass('icon-arrow-right');
    });

    $('#style-switcher a').click(function() {
        var style = $(this).attr('href').replace('#', '');
        $('.skin-color').attr('href', 'css/maruti.' + style + '.css');
        $(this).siblings('a').css({ 'border-color': 'transparent' });
        $(this).css({ 'border-color': '#aaaaaa' });
    });

    $('.lightbox_trigger').click(function(e) {

        e.preventDefault();

        var image_href = $(this).attr("href");

        if ($('#lightbox').length > 0) {

            $('#imgbox').html('<img src="' + image_href + '" /><p><i class="icon-remove icon-white"></i></p>');

            $('#lightbox').slideDown(500);
        } else {
            // var lightbox = 
            '<div id="lightbox" style="display:none;">' +
            '<div id="imgbox"><img src="' + image_href + '" />' +
                '<p><i class="icon-remove icon-white"></i></p>' +
                '</div>' +
                '</div>';

            $('body').append(lightbox);
            $('#lightbox').slideDown(500);
        }

    });


    $('#lightbox').on('click', function() {
        $('#lightbox').hide(200);
    });

    $('.icon-remove').on('click', function() {
        $(this).parent().parent().fadeOut();
        $('.mask').fadeOut();
    })

    $('.confirm-cancel').click(function() {
        $('.confirm-modal,.mask').fadeOut();
    });

    $(document).on('click', '.drop-left', function() {
        $('.drop-left-menu').not($(this).next()).hide();
        $(this).next().toggle();
    })


    // 操作菜单
    $(document).on('click', function(e) {
        var flag = 0;
        for (var i = 0; i < $('.drop-left').length; i++) {
            if (e.target == $('.drop-left')[i]) {
                flag = 1;
            }
        }
        if (flag != 1) {
            $('.drop-left-menu').hide();
        }
    })

    //模态框内下拉菜单
    $(document).on('click', '.a-drop-input', function() {
        $(this).next().slideToggle();
    })
    $(document).on('click', '.a-drop-list:not(".drop-depart") li', function() {
        var val = $(this).html();
        var id = $(this).data("id");
        $(this).parent().prev().val(val);
        $(this).parent().prev().data("id", id);
        $(this).parent().slideUp();
    })

    //项目详情
    $('.tab-info-btn').click(function() {
        $('.tab-info-btn').removeClass('active');
        $(this).addClass('active');
        var a = $('.tab-info-btn').index(this);
        $('.tab-info').hide();
        $('.tab-info').eq(a).fadeIn();

    })

    $('.info-modal').on('click', '.circle-state', function() {
        var a = $('.circle-state').index(this);
        var title = ["承接", "编制", "审定", "盖章", "归档"];
        $('.p-note-title').html('项目' + title[a] + "备注")
        $('.p-note').hide();
        $('.p-note').eq(a).fadeIn();
    })
});


// alert
function setAlert(str, timeAlert) {
    if (typeof(timeAlert) == 'undefined') {
        timeAlert = 1500;
    }
    $('.alert-modal').html(str);
    $('.alert-modal').fadeIn();
    setTimeout(function() {
        $('.alert-modal').fadeOut();
    }, timeAlert);
}

/**
 * [fadeModal 模态框操作]
 * @param  {[String]} modalName [模态框名称]
 */
function fadeModal(modalName) {
    $(modalName).fadeIn();
    $('.mask').fadeIn();
}

/**
 * [setConfirm 设置确认框]
 * @param {[String]}   string   [弹出框文字]
 * @param {Function} callback [为确认按钮绑定事件]
 */
function setConfirm(string, callback) {
    $('.confirm-text').html(string);
    fadeModal('.confirm-modal')
    $('.confirm-btn').on('click', function() {
        callback();
        $('.confirm-modal,.mask').fadeOut();
    })
}

/**
 * [toggleDown 展开/收起]
 * @param  {[String]} btn      [按钮class]
 * @param  {[String]} upIcon   [向上图标class]
 * @param  {[String]} downIcon [向下图标class]
 * @return 
 */
function toggleDown(btn, upIcon, downIcon) {
    $(btn).next().slideToggle();
    $(btn).children('i').toggleClass('icon-xiala icon-shangla')
}

function loading() {
    $('.loading').fadeIn();
}

function loadingHide() {
    $('.loading').fadeOut();
}

/**
 * [transData json格式转树状结构]
 * @param  {[json]} a           [json数据]
 * @param  {[String]} idStr       [id名称]
 * @param  {[String]} pidStr      [父id名称]
 * @param  {[String]} chindrenStr [子节点名称]
 * @return {[Array]}             [转化后的格式]
 */
function transData(a, idStr, pidStr, chindrenStr) {
    var r = [],
        hash = {},
        id = idStr,
        pid = pidStr,
        children = chindrenStr,
        i = 0,
        j = 0,
        len = a.length;
    for (; i < len; i++) {
        hash[a[i][id]] = a[i];
    }
    for (; j < len; j++) {
        var aVal = a[j],
            hashVP = hash[aVal[pid]];
        if (hashVP) {
            !hashVP[children] && (hashVP[children] = []);
            hashVP[children].push(aVal);
        } else {
            r.push(aVal);
        }
    }
    return r;
}

/**
 * [choiseDep 下拉列表选择部门]
 * @param  {[type]}   eleParent [祖先节点：document或三级以上父层(用于绑定动态事件，尽量避免document)]
 * @param  {[type]}   ele       [所绑定事件的元素]
 * @param  {Function} callback  [回调函数,扩展函数操作，根据需要传]
 */

//ajax
var BASEAJAX = {
    dataType: 'json',
}
var BASEPUTAJAX = {
    dataType: 'json',
    traditional: true,
    type: "POST",
    data: {
        _method: "PUT"
    }

};
var BASEDELETEAJAX = {
    dataType: 'json',
    type: "POST",
    traditional: true,
    data: {
        _method: "DELETE"
    }
}
var BASEPOSTAJAX = {
    dataType: 'json',
    data: {},
    traditional: true,
    type: "POST"
}
var BASEGETAJAX = {
    dataType: 'json',
    data: {},
    type: "GET"
}

function getBASEPUTAJAX() {
    var newObject = $.extend(true, {}, BASEPUTAJAX);
    return newObject;
}

function getBASEDELETEAJAX() {
    var newObject = $.extend(true, {}, BASEDELETEAJAX);
    return newObject;
}

function getBASEPOSTAJAX() {
    var newObject = $.extend(true, {}, BASEPOSTAJAX);
    return newObject;
}

function getBASEGETAJAX() {
    var newObject = $.extend(true, {}, BASEGETAJAX);
    return newObject;
}
//写cookies
function setCookie(cname, cvalue, exdays) {
    var d = new Date();
    d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
    var expires = "expires=" + d.toGMTString();
    document.cookie = cname + "=" + cvalue + "; " + expires;
}

//读取cookies
function getCookie(cname) {
    var name = cname + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i].trim();
        if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
    }
    return "";
}

//删除cookies
function delCookie(name) {
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval = getCookie(name);
    if (cval != null)
        document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
}
